package cc.devclub.ftd.thread.lifecycle;

/**
 * Created by loading on 2021/12/13.
 */
public class MyThreadState2 {


    public static void main(String[] args) throws InterruptedException {

        SaleTicket saleTicket = new SaleTicket();

        Thread thread1 = new Thread(saleTicket);
        Thread thread2 = new Thread(saleTicket);

        thread1.start();
        thread2.start();

        Thread.State state1 = thread1.getState();
        Thread.State state2 = thread2.getState();
        // 只要线程未运行结束，就一直输出线程当前的状态
        while (state1 != Thread.State.TERMINATED || state2 != Thread.State.TERMINATED) {

            state1 = thread1.getState();
            state2 = thread2.getState();
            // 观察当前线程状态
            System.out.println("线程1状态为:" + state1);
            System.out.println("线程2状态为:" + state2);
        }
    }
}


class SaleTicket implements Runnable {

    private int ticket = 25;

    @Override
    public void run() {
        while (ticket > 0) {
            sale();
        }
    }

    public synchronized void sale() {
        ticket--;
        System.out.println("剩余票数为:" + ticket);
    }
}
